﻿using System;
using System.Collections.Generic;

namespace JsParser.Cmd.Code
{
    class CommandLineArgumentsParser
    {
        public Settings Parse(string[] args)
        {
            var settings = new Settings();
            Fill(settings, args);
            Validate(settings);
            return settings;
        }

        private static void Validate(Settings settings)
        {
            if (string.IsNullOrWhiteSpace(settings.Include) && string.IsNullOrWhiteSpace(settings.Exclude) &&
                string.IsNullOrWhiteSpace(settings.WorkingDirectory))
            {
                Console.WriteLine(@"
JsParser.Cmd. Command line tool to verify javascript code. Based on visual studio extension: JavascriptParser.
Please specify the next arguments:
-include:*.js           - path masks to include (divided by ';'), this tool can proccess files with the next extensions: js, htm, html, aspx, asp, ascx, master, cshtml
-exclude:*.min.js       - path masks to exclude (divided by ';')(optional)
-directory:c:\myFiles\  - target directory with your source files.
");
                throw  new CommandLineArgumentException();
            }
            else if (string.IsNullOrWhiteSpace(settings.Include) && string.IsNullOrWhiteSpace(settings.WorkingDirectory))
            {
                Console.WriteLine("Please specify: directory and include arguments.");
                throw new CommandLineArgumentException();
            }
        }

        private static void Fill(Settings settings, IEnumerable<string> args)
        {
            foreach (var arg in args)
            {
                if (StartWith(arg, "/?") || StartWith(arg, "help"))
                {
                    continue;
                }
                else if (StartWith(arg, CommandLineArgs.Include))
                {
                    settings.Include = arg.Substring(CommandLineArgs.Include.Length);
                }
                else if (StartWith(arg, CommandLineArgs.Exclude))
                {
                    settings.Exclude = arg.Substring(CommandLineArgs.Exclude.Length);
                }
                else if (StartWith(arg, CommandLineArgs.WorkingDirectory))
                {
                    settings.WorkingDirectory = arg.Substring(CommandLineArgs.WorkingDirectory.Length);
                }
                else throw new ArgumentException("Unknown argument: " + arg);
            }
        }

        private static bool StartWith(string arg, string id)
        {
            return arg.StartsWith(id, StringComparison.OrdinalIgnoreCase);
        }
    }
}
